var express = require('express');
var Request = require('./apiModules/request');
const $request = new Request();
var redis = require('./redisCluster');
var config = require('./config');
var router = express.Router();
var rsa = require('./rsa');
var auth = require('./rights/authentication');
const SSO = require('./rights/sso');

//通用render数据
var renderComData = function () {
  return {
    page: "",
    codeImg: "",
    tenantImage: "",
    userIcon: "",
    userName: "",
    isLogin: false,
    showLogin: true
  }
}
//用户登录成功后显示头像和姓名
var setUserInfo = function (_user, renderData) {
  renderData.isLogin = true;
  renderData.tenantImage = _user.tenantImage ? _user.tenantImage : "";
  renderData.userIcon = _user.userImage ? _user.userImage : `/images/defaultUserIcon_${String(_user.gender) ? _user.gender : "1"}.png`;
  renderData.userName = _user.fullName;
}

// 登录
router.get('/login', async function (req, res, next) {
  const loginSuccessUrl = req.query.state;

  //  跳转到单点登录地址，再回跳回来，会带上code参数
  const getCodeUrl = () => {
    res.redirect(`${config.authUrl}/auth/oauth/authorize?response_type=code&client_id=bdh-bi&redirect_uri=${config.domain}/login&state=${loginSuccessUrl}`)
  }

  const code = req.query.code;

  //  先获取code
  if(!code) return getCodeUrl();

  //  根据code获取accessToken
  const accessTokenInfo = await SSO.getAccessToken(code);

  if(!accessTokenInfo.success) {
    let renderData = { data: accessTokenInfo };
    res.json({status: -1, renderData});
    return;
  }

  //  根据accessToken获取userId
  const userInfo = await SSO.getUserId(accessTokenInfo.data.accessToken);

  if (userInfo.userId) {
    auth.saveJwt( { res: res, tokenInfo: accessTokenInfo.data, tokenKey: userInfo.key, isSaveRefreshToken: true } );

    // return res.redirect("/workbench");
    return res.redirect(loginSuccessUrl);
  }

  res.redirect('/home');
});

/** 登出 */
router.get('/logout', async function (req, res, next) {
  // await SSO.logout();

  //清除用户登录信息
  auth.logoutFun(req, res);

  res.redirect(config.authUrl + "/auth/logout");
});

/* 首页 */
router.get('/*', function (req, res, next) {
  res.render('index.html');
});

const allPath = require("./rights/routing");
//读取路由配置并加权限控制
allPath && allPath.map(_path => {
  router.get(_path.uri, (req, res, next) => {
    //如未配置key则取uri作为权限鉴定依据
    checkRouterAuth(req, res, _path);
  });
});
//校验请求登录状态和请求地址权限
let checkRouterAuth = async function (req, res, _path) {
  let tokenUser = await auth.checkRouterAuth(req, res);
  if (tokenUser) {
    //共有资源不做权限控制
    if (_path.common) {
      res.render('workbench.html');
      return;
    }
    let flag = await auth.checkUriAuth(tokenUser, _path.uri);
    if (flag) {
      //子项目 工作台页需要修改此处
      res.render('home.html');
    }
    else {
      //资源不可用
      auth.to403(req, res, {
        status: -1,
        message: __("original.page_notavailable"),
        path: config.domain + "/home",
      });
    }
  }
  else {
    //跳转错误面-未登录
    auth.to403(req, res, {
      status: -2,
      message: __("original.common_userlogin_outdatetorelogin"),
      path: config.domain + "/login",
    });
  }
}
module.exports = router;
